import { defineStore } from 'pinia'
import { 
  getHistoryImages, 
  getDownloadedImages,
  downloadImage,
  deleteDownloadRecord,
  getEncodedImages,
  deleteImage,
  inpaintImage,
} from '@/apis/users/api.js'

export const useImagesStore = defineStore('images', {
  state: () => ({
    historyImages: [
      // {
      //   imgCode:'https://ts1.cn.mm.bing.net/th?id=OIP-C.tFY0UlhYai223khEsA56lwHaHa&w=250&h=250&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2',
        // downloadTime:'2024-12-1',
        // createTime:'2024',
      //   prompt: "sdaaaaaaa",
      // },
    ],
    downloadedImages: [],
    encodedImages: '',
    uploadmask:'',
  }),
  
  actions: {
    // 生成获取编码后的图片
    async fetchEncodedImages(prompt) {
      const data = await getEncodedImages(prompt)
      this.encodedImages = data;
    },

    // 获取历史图片
    async fetchHistoryImages() {
      const data = await getHistoryImages()
      const baseUrl = "http://192.168.1.13:8124/static/temp/";
      this.historyImages = Object.keys(data)
      .filter(key => key.startsWith("img"))
      .map((key, index) => ({
          id: `img${index}`,
          prompt: data[`pro${index}`],
          imgUrl: `${baseUrl}${data[`img${index}`]}`
      }))
    },
    
    // 局部重绘 上传图片
    async inpaintImage(maskImage) {
      const data = await inpaintImage(maskImage)
      this.uploadmask = data.filename
    },

    async deleteHistoryImage(index) {
      this.historyImages = this.historyImages.filter(img => img.id !== index)
      await deleteImage(index)
    },

    async fetchDownloadedImages() {
      const { data } = await getDownloadedImages()
      this.downloadedImages = data
    },
    
    async downloadImage(imageId) {
      await downloadImage(imageId)
      await this.fetchDownloadedImages()
    },
    
    async deleteDownload(id) {
      await deleteDownloadRecord(id)
      await this.fetchDownloadedImages()
    }
  }
})
